<?php
global $_W,$_GPC;

$settings = get("select kwords from ".tb('kword')." where uniacid='{$_W['uniacid']}'");
$set = unserialize($settings['kwords']);
if (checksubmit('submit')){
	$kword = $_GPC['kword'];
	$gid = $_GPC['gid'];
	$tips = $_GPC['tips'];
	
	foreach ($kword as $k => $value) {
		if (empty($value) || empty($gid[$k])) continue;
		$kws[] = array('kword'=>$value,'fgid'=>$gid[$k],'tips'=>$tips[$k]);
	}
	if ($settings){
		update('kword',array('kwords'=>serialize($kws)),array('uniacid'=>$_W['uniacid']));
	}else insert('kword',array('kwords'=>serialize($kws),'uniacid'=>$_W['uniacid']));
	
	$rule = get("select id from ".tablename('rule')." where uniacid='{$_W['uniacid']}' and module='junsion_wxtools' and name='junsion_wxtools_kw'");
	if (empty($rule)){
		$rule = array(
			'uniacid' => $_W['uniacid'],
			'name' => 'junsion_wxtools_kw',
			'module' => $this->modulename,
			'status' => 1,
			'displayorder' => 254,
		);
		pdo_insert('rule',$rule);
		$rule['id'] = pdo_insertid();
	}
	foreach ($set as $value) {
		$okws[] = $value['kword'];
	}
	$diff = array_diff($okws, $kword);
	foreach ($kword as $value) {
		if (empty($value)) continue;
		$rk = pdo_fetch('select id from '.tablename('rule_keyword')." where rid='{$rule['id']}' and content='{$value}' limit 1");
		if (empty($rk)){
			$rulew = array(
				'uniacid' => $_W['uniacid'],
				'module' => $this->modulename,
				'status' => 1,
				'displayorder' => 254,
				'type'=>1,
				'rid'=>$rule['id'],
				'content'=>$value,
			);
			pdo_insert('rule_keyword',$rulew);
		}else pdo_update('rule_keyword',array('content'=>$value),array('id'=>$rk['id']));
	}
	
	foreach ($diff as $value) {
		pdo_delete('rule_keyword',array('content'=>$value,'rid'=>$rule['id']));
	}
	MSG('修改成功','referer');
}

$fgroups = pdo_fetch('SELECT * FROM ' . tablename('mc_fans_groups') . ' WHERE uniacid = :uniacid', array(':uniacid' => $_W['uniacid']));
$fgroups = unserialize($fgroups['groups']) ? unserialize($fgroups['groups']) : array();
include $this->template('kwordgroup');